package main

import (
	"encoding/json"
	"io/ioutil"
	"os"
)

// BackupConfigFileName 为后备配置文件，在本目录找不到的话，就找下面这个文件
const BackupConfigFileName = "./configs/monitord.json"

type AlarmCallT struct {
	Host      string
	TaskUuid  string
	FrameId   int
	Customers []struct {
		Cid      int
		Tid      string
		Schedule []struct {
			Start int
			End   int
			Phone string
		}
	}
}

type Config struct {
	fileName string

	Port           int
	KeyFile        string
	CertFile       string
	DBUrl          string
	DBName         string
	DBUser         string //数据库用户名
	DBPwd          string //数据库密码
	HTTPS          bool   //HTTPS: true false
	AlarmId        string
	GpsInterval    int
	AlarmInterval  int
	CheckAccessUrl string
	AlarmCall      AlarmCallT
}

func loadConfig(file string) (*Config, error) {
	if file == "" {
		file = os.Args[0] + ".json"
	}
	if _, err := os.Stat(file); os.IsNotExist(err) {
		file = BackupConfigFileName
	}
	buf, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}

	var cfg Config
	err = json.Unmarshal(buf, &cfg)
	if err == nil {
		cfg.fileName = file
	}
	if cfg.GpsInterval == 0 {
		cfg.GpsInterval = 1
	}
	if cfg.AlarmInterval == 0 {
		cfg.AlarmInterval = 1
	}

	return &cfg, err
}

func (p *Config) Save() error {
	buf, _ := json.MarshalIndent(p, "", "\t")

	return ioutil.WriteFile(p.fileName, buf, os.ModePerm)
}
